package cn.com.dbappsecurity.frame.paramparse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import cn.com.dbappsecurity.frame.annotations.Validate;
import cn.com.dbappsecurity.frame.exception.FrameException;

public class ParamString implements IParamParse{

	private String name;
	private Validate validate;
	private boolean array;
	private boolean paramTrim;
	
	public ParamString(boolean paramTrim,String name,boolean array,Validate validate){
		this.paramTrim = paramTrim;
		this.name = name;
		this.array = array;
		this.validate = validate;
	}
	
	@Override
	public Object getParamter(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String[] values = request.getParameterValues(name);
		if(!validate(values)){
			throw new FrameException(FrameException.TYPE_ARGU_ERROR);
		}
		if(paramTrim && values != null){
			for(int i=0;i<values.length;i++){
				if(values[i] != null){
					values[i] = values[i].trim();
				}
			}
		}
		return array ? values : (values == null || values.length == 0 ? null : values[0]);
	}
	
	private boolean validate(String[] value) {
		if(validate != null){
			if(validate.required() && value.length == 0){
				return false;
			}
			for(String val : value){
				if(validate.required() && StringUtils.isBlank(val)){
					return false;
				}
				double minLen = validate.minLen();
				if(minLen != -1){
					if(val.length() < minLen){
						return false;
					}
				}
				double maxLen = validate.maxLen();
				if(maxLen != -1){
					if(val.length() > maxLen){
						return false;
					}
				}
				String regex = validate.regex();
				if(!StringUtils.isBlank(regex)){
					if(!val.matches(regex)){
						return false;
					}
				}
			}
		}
		return true;
	}
	
}
